<?php

namespace app\model\oa;

use think\Model;
use think\model\concern\SoftDelete;

/**
 * 公文管理模型
 * @package app\model\oa
 */
class OfficialDocs extends Model
{
    use SoftDelete;

    // 表名
    protected $name = 'official_docs';

    // 主键
    protected $pk = 'id';

    // 自动时间戳
    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';

    // 字段类型转换
    protected $type = [
        'id' => 'integer',
        'title' => 'string',
        'doc_no' => 'string',
        'type' => 'integer',
        'level' => 'integer',
        'content' => 'string',
        'author_id' => 'integer',
        'dept_id' => 'integer',
        'receiver_id' => 'integer',
        'status' => 'integer',
        'urgency' => 'integer',
        'attachment' => 'json',
        'sign_info' => 'json',
        'approval_info' => 'json',
        'issue_time' => 'int',
        'receive_time' => 'int',
        'deadline' => 'int',
        'create_time' => 'int',
        'update_time' => 'int',
        'delete_time' => 'int',
    ];

    // 公文类型常量
    const TYPE_NOTICE = 1;        // 通知
    const TYPE_CIRCULAR = 2;      // 通报
    const TYPE_REPORT = 3;        // 报告
    const TYPE_REQUEST = 4;       // 请示
    const TYPE_REPLY = 5;         // 批复
    const TYPE_LETTER = 6;        // 函件
    const TYPE_MINUTES = 7;       // 会议纪要
    const TYPE_DECISION = 8;      // 决定

    // 公文级别常量
    const LEVEL_URGENT = 1;       // 特急
    const LEVEL_IMPORTANT = 2;    // 加急
    const LEVEL_NORMAL = 3;       // 平急

    // 公文状态常量
    const STATUS_DRAFT = 0;           // 草稿
    const STATUS_PENDING = 1;         // 待签发
    const STATUS_ISSUED = 2;          // 已签发
    const STATUS_RECEIVED = 3;       // 已接收
    const STATUS_ARCHIVED = 4;        // 已归档
    const STATUS_EXPIRED = 5;         // 已过期

    /**
     * 获取类型文本
     */
    public static function getTypeText($type)
    {
        $texts = [
            self::TYPE_NOTICE => '通知',
            self::TYPE_CIRCULAR => '通报',
            self::TYPE_REPORT => '报告',
            self::TYPE_REQUEST => '请示',
            self::TYPE_REPLY => '批复',
            self::TYPE_LETTER => '函件',
            self::TYPE_MINUTES => '会议纪要',
            self::TYPE_DECISION => '决定',
        ];
        return $texts[$type] ?? '未知';
    }

    /**
     * 获取级别文本
     */
    public static function getLevelText($level)
    {
        $texts = [
            self::LEVEL_URGENT => '特急',
            self::LEVEL_IMPORTANT => '加急',
            self::LEVEL_NORMAL => '平急',
        ];
        return $texts[$level] ?? '未知';
    }

    /**
     * 获取状态文本
     */
    public static function getStatusText($status)
    {
        $texts = [
            self::STATUS_DRAFT => '草稿',
            self::STATUS_PENDING => '待签发',
            self::STATUS_ISSUED => '已签发',
            self::STATUS_RECEIVED => '已接收',
            self::STATUS_ARCHIVED => '已归档',
            self::STATUS_EXPIRED => '已过期',
        ];
        return $texts[$status] ?? '未知';
    }

    /**
     * 关联作者
     */
    public function author()
    {
        return $this->belongsTo('app\model\admin\User', 'author_id', 'id');
    }

    /**
     * 关联部门
     */
    public function department()
    {
        return $this->belongsTo('app\model\admin\Department', 'dept_id', 'id');
    }

    /**
     * 关联接收人
     */
    public function receiver()
    {
        return $this->belongsTo('app\model\admin\User', 'receiver_id', 'id');
    }

    /**
     * 获取公文列表
     */
    public static function getList($params = [])
    {
        $query = self::with(['author', 'department', 'receiver'])->order('create_time', 'desc');

        // 按类型筛选
        if (!empty($params['type'])) {
            $query->where('type', $params['type']);
        }

        // 按级别筛选
        if (!empty($params['level'])) {
            $query->where('level', $params['level']);
        }

        // 按状态筛选
        if (isset($params['status']) && $params['status'] !== '') {
            $query->where('status', $params['status']);
        }

        // 按作者筛选
        if (!empty($params['author_id'])) {
            $query->where('author_id', $params['author_id']);
        }

        // 按部门筛选
        if (!empty($params['dept_id'])) {
            $query->where('dept_id', $params['dept_id']);
        }

        // 按接收人筛选
        if (!empty($params['receiver_id'])) {
            $query->where('receiver_id', $params['receiver_id']);
        }

        // 按标题搜索
        if (!empty($params['title'])) {
            $query->where('title', 'like', '%' . $params['title'] . '%');
        }

        // 按文号搜索
        if (!empty($params['doc_no'])) {
            $query->where('doc_no', 'like', '%' . $params['doc_no'] . '%');
        }

        // 按内容搜索
        if (!empty($params['content'])) {
            $query->where('content', 'like', '%' . $params['content'] . '%');
        }

        // 紧急程度优先
        $query->order('level', 'asc')->order('create_time', 'desc');

        return $query->paginate($params['limit'] ?? 15);
    }

    /**
     * 获取待签发公文
     */
    public static function getPendingDocs($params = [])
    {
        $params['status'] = self::STATUS_PENDING;
        return self::getList($params);
    }

    /**
     * 获取已签发公文
     */
    public static function getIssuedDocs($params = [])
    {
        $params['status'] = self::STATUS_ISSUED;
        return self::getList($params);
    }

    /**
     * 获取已接收公文
     */
    public static function getReceivedDocs($userId, $params = [])
    {
        $params['receiver_id'] = $userId;
        $params['status'] = self::STATUS_RECEIVED;
        return self::getList($params);
    }

    /**
     * 获取紧急公文
     */
    public static function getUrgentDocs($params = [])
    {
        $params['level'] = self::LEVEL_URGENT;
        return self::getList($params);
    }

    /**
     * 签发公文
     */
    public function issue($signInfo = [])
    {
        $this->status = self::STATUS_ISSUED;
        $this->issue_time = date('Y-m-d H:i:s');
        
        // 更新签发信息
        $signData = $this->sign_info ?: [];
        $signData[] = array_merge($signInfo, [
            'action' => 'issue',
            'time' => date('Y-m-d H:i:s'),
        ]);
        $this->sign_info = $signData;
        
        $this->save();
    }

    /**
     * 接收公文
     */
    public function receive($receiveInfo = [])
    {
        $this->status = self::STATUS_RECEIVED;
        $this->receive_time = date('Y-m-d H:i:s');
        
        // 更新签收信息
        $signData = $this->sign_info ?: [];
        $signData[] = array_merge($receiveInfo, [
            'action' => 'receive',
            'time' => date('Y-m-d H:i:s'),
        ]);
        $this->sign_info = $signData;
        
        $this->save();
    }

    /**
     * 归档公文
     */
    public function archive()
    {
        $this->status = self::STATUS_ARCHIVED;
        $this->save();
    }

    /**
     * 检查是否已过期
     */
    public function isExpired()
    {
        return $this->deadline && strtotime($this->deadline) < time();
    }

    /**
     * 获取即将到期的公文
     */
    public static function getExpiringDocs($days = 3)
    {
        $expiryDate = date('Y-m-d', strtotime("+$days days"));
        return self::where('deadline', '<=', $expiryDate)
            ->where('status', '<>', self::STATUS_ARCHIVED)
            ->where('status', '<>', self::STATUS_EXPIRED)
            ->order('deadline', 'asc')
            ->select();
    }

    /**
     * 搜索器 - 标题
     */
    public function searchTitleAttr($query, $value)
    {
        $query->where('title', 'like', '%' . $value . '%');
    }

    /**
     * 搜索器 - 文号
     */
    public function searchDocNoAttr($query, $value)
    {
        $query->where('doc_no', 'like', '%' . $value . '%');
    }

    /**
     * 搜索器 - 内容
     */
    public function searchContentAttr($query, $value)
    {
        $query->where('content', 'like', '%' . $value . '%');
    }

    /**
     * 搜索器 - 类型
     */
    public function searchTypeAttr($query, $value)
    {
        $query->where('type', $value);
    }

    /**
     * 搜索器 - 级别
     */
    public function searchLevelAttr($query, $value)
    {
        $query->where('level', $value);
    }

    /**
     * 搜索器 - 状态
     */
    public function searchStatusAttr($query, $value)
    {
        $query->where('status', $value);
    }

    /**
     * 搜索器 - 作者ID
     */
    public function searchAuthorIdAttr($query, $value)
    {
        $query->where('author_id', $value);
    }

    /**
     * 搜索器 - 部门ID
     */
    public function searchDeptIdAttr($query, $value)
    {
        $query->where('dept_id', $value);
    }

    /**
     * 搜索器 - 接收人ID
     */
    public function searchReceiverIdAttr($query, $value)
    {
        $query->where('receiver_id', $value);
    }

    /**
     * 搜索器 - 签发时间范围
     */
    public function searchIssueTimeAttr($query, $value)
    {
        if (is_array($value) && count($value) == 2) {
            $query->whereBetween('issue_time', $value);
        }
    }

    /**
     * 搜索器 - 截止时间范围
     */
    public function searchDeadlineAttr($query, $value)
    {
        if (is_array($value) && count($value) == 2) {
            $query->whereBetween('deadline', $value);
        }
    }

    /**
     * 搜索器 - 创建时间范围
     */
    public function searchCreateTimeAttr($query, $value)
    {
        if (is_array($value) && count($value) == 2) {
            $query->whereBetween('create_time', $value);
        }
    }
}